package jp.co.sharp.android.parents.kidsguard.activity.sendImage;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.ContactAvatarAddActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.sendImage.dialog.DealWithSendImageDlg;
import jp.co.sharp.android.parents.kidsguard.activity.sendImage.dialog.PreviewDlg;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PowerSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

public class PreviewActivity extends AppCompatActivity {

    private App mApp;

    private ImageView mBackIv;

    private Button mSendImageBtn;

    private Button mCutBtn;

    private ImageView mPreviewImageIv;

    private ImageView mRotateIv;

    private Bitmap mBitmapOpen;

//    private String imagePath;

    private Boolean mSendFlag = false;

    private static final int REQUEST_ALBUM_OK = 1000;

    private CorpToView mCorpToView;

    private TextView mTitleTv;

    private String mSendUrl;

    private final static int  SEND_IMAGE  = 10 ;

    private final static int  SEND_UN_IMAGE  = 11 ;

    private static final int SEND_KID_EXIT = 5;

    private static final int SEND_KID_IS_USING = 0;

    private static final int SEND_KID_ENTER = 1;

    public ParentBleTransfer mParentBleTransfer;

    private String mMacAddress;

    private DealWithSendImageDlg mDealWithSendImageDlg;

    private Boolean mOnSyncResultFlag = false;

    private KidInfoEntity mKidInfoEntity;

    private DealWithWaitingDlg mDealWithWaitingDlg;

    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;

    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        mApp = (App)getApplication();
        mounted();
        initReceiver();
    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "PreviewActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PreviewActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if ((mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT)&&(!mEditReopening)) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(PreviewActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mEditReopening = true;
                    sendIsUsingToKid();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                }
                mSystemHomeFlag = false;
            }
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "PreviewActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "PreviewActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "PreviewActivity_onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        initReceiver();
        switch (requestCode) {
            case REQUEST_ALBUM_OK:
                ContentResolver resolver = getContentResolver();
                try {
                    Uri uri = data.getData();
                    InputStream inputStream = resolver.openInputStream(uri);
                    mBitmapOpen = BitmapFactory.decodeStream(inputStream);
                    mPreviewImageIv.setImageBitmap(mBitmapOpen);
//                    imagePath = getRealPathFromUri(this,uri);
                    sendIsUsingToKid();
                } catch (FileNotFoundException e) {
                    Log.e(TAG,e.getMessage());
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Log.i(TAG, "PreviewActivity_onBackPressed");
        super.onBackPressed();
        if (mDealWithSendImageDlg != null && mDealWithSendImageDlg.isShowing()){
            DelDeviceConfirmDlg delDeviceConfirmDlg = new DelDeviceConfirmDlg(PreviewActivity.this, R.style.commonDlg, "画像送信を取り消しますか？");
            delDeviceConfirmDlg.show();
            delDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    new PreviewActivityThread(SEND_UN_IMAGE).start();
                    sendExitToKid();
                    mDealWithSendImageDlg.dismiss();
                }
            });
        }else {
            sendExitToKid();
        }
    }

    private void mounted(){
        Log.i(TAG, "PreviewActivity_mounted");
        mKidInfoEntity = ((App)getApplication()).findKidInfoBySelect();
        mBackIv=(ImageView)findViewById(R.id.imageViewBack);
        mSendImageBtn=(Button)findViewById(R.id.buttonSendImage);
        mPreviewImageIv=(ImageView)findViewById(R.id.imageViewPreviewImage);
        mCorpToView=(CorpToView)findViewById(R.id.corpToView);
        mCutBtn=(Button)findViewById(R.id.buttonCut);
        mRotateIv=(ImageView)findViewById(R.id.imageViewRotate);
        mTitleTv=(TextView) findViewById(R.id.tvTitle);
        mMacAddress = ((App) getApplication()).findKidInfoBySelect().getMacAddress();
        mCorpToView.setVisibility(View.GONE);
        mCutBtn.setVisibility(View.GONE);
        mRotateIv.setVisibility(View.GONE);
        mSendImageBtn.setVisibility(View.VISIBLE);
        mPreviewImageIv.setVisibility(View.VISIBLE);
        mTitleTv.setText("画像プレビュー");
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mSendFlag){
                    mCorpToView.setVisibility(View.GONE);
                    mCutBtn.setVisibility(View.GONE);
                    mRotateIv.setVisibility(View.GONE);
                    mSendImageBtn.setVisibility(View.VISIBLE);
                    mPreviewImageIv.setVisibility(View.VISIBLE);
                    mTitleTv.setText("画像プレビュー");
                    mSendFlag = false;
                }else {
                    sendExitToKid();
                }
            }
        });
        mSendImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mSendFlag){
                    createUrl();
                    CommonUtils.saveMyBitmap(mSendUrl, mBitmapOpen);
                    new PreviewActivityThread(SEND_IMAGE).start();
                    mDealWithSendImageDlg = new DealWithSendImageDlg(PreviewActivity.this,R.style.commonDlg);
                    mDealWithSendImageDlg.show();
                }else {
                    PreviewDlg previewDlg = new PreviewDlg(PreviewActivity.this,R.style.commonDlg);
                    previewDlg.show();
                    previewDlg.setCutImageListener(new PreviewDlg.OnCutImageListener() {
                        @Override
                        public void onOperateSet() {
                            mCorpToView.setVisibility(View.VISIBLE);
                            mCorpToView.showImage(mBitmapOpen);
                            mCutBtn.setVisibility(View.VISIBLE);
                            mRotateIv.setVisibility(View.VISIBLE);
                            mSendImageBtn.setVisibility(View.GONE);
                            mPreviewImageIv.setVisibility(View.GONE);
                            mTitleTv.setText("画像トリミング");
                            mSendFlag = true;
                            previewDlg.dismiss();
                        }
                    });
                    previewDlg.setSendOriginImageListener(new PreviewDlg.OnSendOriginImageListener() {
                        @Override
                        public void onOperateSet() {
                            createUrl();
                            CommonUtils.saveMyBitmap(mSendUrl, mBitmapOpen);
                            new PreviewActivityThread(SEND_IMAGE).start();
                            previewDlg.dismiss();
                            mDealWithSendImageDlg = new DealWithSendImageDlg(PreviewActivity.this,R.style.commonDlg);
                            mDealWithSendImageDlg.show();
                        }
                    });
                }
            }
        });
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, REQUEST_ALBUM_OK);

    }

    private void createUrl(){
        Log.i(TAG, "PreviewActivity_createUrl");
        StringBuilder builder = new StringBuilder();
        builder.append(getFilesDir().getPath().toString());
        builder.append("/");
        builder.append("sendImage");
        builder.append(String.valueOf((new Date()).getTime()));
        builder.append(".png");
        mSendUrl=builder.toString();
    }

    public void rotate90(View view) {
        mCorpToView.rotate90();
    }

    public void cut(View view) {
        Log.i(TAG, "PreviewActivity_cut");
        mBitmapOpen = mCorpToView.getClipRectImage();
        mPreviewImageIv.setImageBitmap(mBitmapOpen);
        mCorpToView.setVisibility(View.GONE);
        mCutBtn.setVisibility(View.GONE);
        mRotateIv.setVisibility(View.GONE);
        mSendImageBtn.setVisibility(View.VISIBLE);
        mPreviewImageIv.setVisibility(View.VISIBLE);
        mTitleTv.setText("画像プレビュー");
        mSendFlag = true;

    }

    /**
     * Receiver
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_FILE_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            String message = "編集を再開しています...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(PreviewActivity.this, R.style.commonDlg, message, false);
                            mDealWithWaitingDlg.show();
                            mScreenOperate = true;
                            mEditReopening = true;
                            sendIsUsingToKid();
                            // ブロードキャストの再登録
                            unregisterReceiver(systemReceiver);
                            initReceiver();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (((App)getApplication()).isMimamoriCheck(macAddress)) {
                        ((App)getApplication()).addmLsIsMimamori(macAddress);
                        sendExitToKid();
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(PreviewActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App)getApplication()).updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PreviewActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(PreviewActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };


    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                try {
                    JSONObject resp = new JSONObject(bluetoothReceiverDto.getRetStr());
                    String method = resp.getString("method");

                    if (null != method) {
                        if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                            if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                                //发送enter
                                sendEnterToKid();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PreviewActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                        // ページジャンプ
                                        mPageJumpFlag = true;
                                        PreviewActivity.this.finish();
                                    }
                                });
                            }
                        } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(method)) {

                        } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(method)){
                            String message = "キッズケータイが操作されました。編集を中断します。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PreviewActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    back();
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                    Log.e(TAG,e.getMessage());
                }

            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                //isFinish
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    if (!mScreenOperate) {

                    } else {
                        mEditReopening = false;
                        mScreenOperate = false;
                        handler.sendEmptyMessage(0);
                    }
                    if (mOnSyncResultFlag) {
                        mOnSyncResultFlag = false;
                        if (!mScreenOperate) {
                            back();
                        }
                    }

                }
            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_FILE_CHANGED.equals(action)) {
                Float imgSendProcess = intent.getFloatExtra("imgSendProcess",0f);
                mDealWithSendImageDlg.editProcess(imgSendProcess);
                if (imgSendProcess == 100f){
                    mDealWithSendImageDlg.dismiss();
                    sendExitToKid();
                }

            }
        }
    };

    private void back() {
        Log.i(TAG, "PreviewActivity_back");
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, HomeActivity.class);
        startActivity(intent);
    }

    /**
     *  is using
     */
    public void sendIsUsingToKid()  {
        Log.i(TAG, "PreviewActivity_sendIsUsingToKid");
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method","getOperatingState");
            jsonObject.put("data",JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }catch (Exception e){
             Log.e(TAG,e.getMessage());
        }
    }


    /**
     * enter
     */
    public void sendEnterToKid(){
        Log.i(TAG, "PreviewActivity_sendEnterToKid");
        new BusinessThread(Constants.SEND_KID_ENTER,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_SEND_IMAGE).start();
    }
    /**
     * exit
     */
    public void sendExitToKid(){
        Log.i(TAG, "PreviewActivity_sendExitToKid");
        mOnSyncResultFlag = true;
        new BusinessThread(Constants.SEND_KID_EXIT,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_SEND_IMAGE).start();

    }



    public static String getRealPathFromUri(Context context, Uri uri) {
        Log.i(TAG, "PreviewActivity_getRealPathFromUri");
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion >= 19) { // api >= 19
            return getRealPathFromUriAboveApi19(context, uri);
        } else { // api < 19
            return getRealPathFromUriBelowAPI19(context, uri);
        }
    }


    private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
        Log.i(TAG, "PreviewActivity_getRealPathFromUriBelowAPI19");
        return getDataColumn(context, uri, null, null);
    }


    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        Log.i(TAG, "PreviewActivity_getRealPathFromUriAboveApi19");
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())){
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            filePath = uri.getPath();
        }
        return filePath;
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Log.i(TAG, "PreviewActivity_getDataColumn");
        String path = null;
        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        Log.i(TAG, "PreviewActivity_isMediaDocument");
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        Log.i(TAG, "PreviewActivity_isDownloadsDocument");
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private class PreviewActivityThread extends Thread {
        private int mViewProcess = SEND_KID_IS_USING;
        /**
         * 0: isUsing, 1: enter , 2: getInfo , 3: setInfo, 4 :exit
         * @param pViewProcess
         */
        public PreviewActivityThread(int pViewProcess) {
            this.mViewProcess = pViewProcess;
        }
        @Override
        public void run() {
            previewActivityProcess(mViewProcess);
        }
    }

    /**
     * 0: isUsing, 1: enter , 2: getInfo , 3: setInfo, 4 :exit
     * @param pViewProcess
     */
    private void previewActivityProcess(int pViewProcess) {
        //
        switch(pViewProcess) {
            case SEND_IMAGE:
                //isUsing
                mParentBleTransfer.writePhotoFile(mMacAddress, mSendUrl);
                break;
            case SEND_UN_IMAGE:
                mParentBleTransfer.cancelWritePhotoFile(mMacAddress);
                break;
        }
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };

}
